// 获取所有书签
async function getAllBookmarks() {
    return new Promise(resolve => {
      chrome.bookmarks.getTree(tree => resolve(tree));
    });
  }
  
  // 扁平化书签树结构
  function flattenBookmarks(nodes, result = []) {
    nodes.forEach(node => {
      if (node.url) {
        result.push({
          title: node.title,
          url: node.url,
          dateAdded: node.dateAdded
        });
      }
      if (node.children) {
        flattenBookmarks(node.children, result);
      }
    });
    return result;
  }
  
  // 发送API请求
  async function sendBookmarksToAPI(bookmarksData, searchQuery, token) {
    try {
      const response = await fetch('https://api.siliconflow.cn/v1/chat/completions', {
        method: 'POST',
        headers: {
          'Authorization': `Bearer sk-nrvjihoykgbjabnelziszukgkcankraqcwtvohvpcuepuyyz`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          model: "deepseek-ai/DeepSeek-V3",
          messages: [{
            role: "user",
            content: `请根据用户的搜索词 "${searchQuery}"，从以下书签列表中选出来关联性最强的书签title和url：${JSON.stringify(bookmarksData)}`
          }],
          max_tokens: 512,
          temperature: 0.7
        })
      });
  
      if (!response.ok) {
        const errorText = await response.text();
        throw new Error(`API请求失败: ${response.status} - ${errorText}`);
      }
      const data = await response.json();
      console.log('API响应数据:', data);
      return data.choices[0].message.content;
    } catch (error) {
      console.error('API请求错误:', error);
      throw error;
    }
  }
  
  // 获取API Token
  async function getAPIToken() {
    return 'sk-nrvjihoykgbjabnelziszukgkcankraqcwtvohvpcuepuyyzsk-nrvjihoykgbjabnelziszukgkcankraqcwtvohvpcuepuyyz';
  }
  
  // 处理搜索
  async function handleSearch() {
    const searchInput = document.getElementById('searchInput');
    const resultList = document.getElementById('results');
    const searchQuery = searchInput.value.trim();
  
    if (!searchQuery) {
      resultList.innerHTML = '<div>请输入搜索关键词</div>';
      return;
    }
  
    resultList.innerHTML = '<div>正在搜索...</div>';
  
    try {
      const bookmarkTree = await getAllBookmarks();
      const bookmarks = flattenBookmarks(bookmarkTree);
      const token = await getAPIToken();
      const aiResponse = await sendBookmarksToAPI(bookmarks, searchQuery, token);
  
      resultList.innerHTML = '';
      const responseDiv = document.createElement('div');
      responseDiv.textContent = aiResponse;
      resultList.appendChild(responseDiv);
    } catch (error) {
      resultList.innerHTML = `<div>搜索失败: ${error.message}</div>`;
    }
  }
  
  // DOM加载完成后绑定事件
  document.addEventListener('DOMContentLoaded', () => {
    const searchInput = document.getElementById('searchInput');
    if (searchInput) {
      searchInput.addEventListener('keypress', (e) => {
        if (e.key === 'Enter') {
          handleSearch();
        }
      });
    } else {
      console.error('搜索输入框未找到');
    }
  });